package com.dmz.proxy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * @author lee
 */
@Configuration
public class HttpOnlyCookieConfig {

    @Bean
    public Filter httpOnlyCookieFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, 
                                          HttpServletResponse response, 
                                          javax.servlet.FilterChain filterChain) 
                    throws javax.servlet.ServletException, IOException {
                
                // 使用自定义的响应包装器
                HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(response) {
                    @Override
                    public void addCookie(Cookie cookie) {
                        // 为所有Cookie设置HttpOnly属性
                        cookie.setHttpOnly(true);
                        // 根据需要设置其他安全属性
                        cookie.setSecure(true); // 仅HTTPS传输
                        cookie.setPath("/");
                        super.addCookie(cookie);
                    }
                };
                
                filterChain.doFilter(request, wrappedResponse);
            }
        };
    }
}